package com.example.dts.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dts.mapper.FileMapper;
import com.example.dts.model.File;
import com.example.dts.model.ro.FileRO;
import com.example.dts.model.vo.PageVO;
import com.example.dts.service.FileService;
import com.example.dts.type.FileType;
import com.example.dts.utils.SpringUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;

@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Value("${bannerPath}")
    private String bannerPath;

    @Value("${domainName}")
    private String domainName;

    @Value("${server.port}")
    private String port;
    @Resource
    private FileMapper fileMapper;

    @Resource
    private SpringUtil springUtil;

    public void saveFile(File file, String userId) {
        this.save(file);
    }

    @Override
    public String uploadBanner(MultipartFile file, String userId) {
        System.out.println("上传轮播图");
        String fileName = file.getOriginalFilename();
        java.io.File dest = new java.io.File(bannerPath + fileName);
        byte environ = springUtil.getEnviron();
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = "";
        if (environ == 0) {
            url = domainName + ":" + port + bannerPath.substring(16) + fileName;
        } else {
            url = domainName + ":" + port + bannerPath.substring(19) + fileName;
        }
        com.example.dts.model.File file1 = new com.example.dts.model.File();
        file1.setType(FileType.BANNER);
        file1.setPath(bannerPath);
        file1.setUrl(url);
        file1.setName(fileName);
        file1.setSize(this.getFileSize(bannerPath + fileName));
        file1.setCreateUserId(userId);
        this.saveFile(file1, userId);
        System.out.println("轮播图上传成功，url：" + url);
        return url;
    }

    public String getFileSize(String fileUrl) {
        int GB = 1024 * 1024 * 1024;//定义GB的计算常量
        int MB = 1024 * 1024;//定义MB的计算常量
        int KB = 1024;//定义KB的计算常量
        try {
            // 加载文件
            java.io.File f = new java.io.File(fileUrl);
            long size = f.length();
            // 格式化小数
            DecimalFormat df = new DecimalFormat("0.00");
            String resultSize = "";
            if (size / GB >= 1) {
                //如果当前Byte的值大于等于1GB
                resultSize = df.format(size / (float) GB) + "GB";
            } else if (size / MB >= 1) {
                //如果当前Byte的值大于等于1MB
                resultSize = df.format(size / (float) MB) + "MB";
            } else if (size / KB >= 1) {
                //如果当前Byte的值大于等于1KB
                resultSize = df.format(size / (float) KB) + "KB";
            } else {
                resultSize = size + "B";
            }
            return resultSize;
        } catch (Exception e) {
            log.error("计算图片尺寸产生错误：", e);
            return null;
        }
    }

    @Override
    public PageVO<File> page(FileRO ro, String userId) {
        QueryWrapper<File> qw = new QueryWrapper<>();
        qw.eq("type",ro.getType());
        qw.eq("deleted",0);
        Page<File> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(Long.parseLong(ro.getCurrentPage()),Long.parseLong(ro.getPageSize()));
        IPage<File> IPage = fileMapper.selectPage(page,qw);
        PageVO<File> page1 = new PageVO<>();
        page1.setPages(IPage.getPages());
        page1.setTotal(IPage.getTotal());
        page1.setRecords(IPage.getRecords());
        return page1;
    }

    @Override
    public void update(File file, String userId) {
        this.updateById(file);
    }

    @Override
    public void deleteBatch(List<String> ids) {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        queryWrapper.eq("deleted",0);
        List<File> files = fileMapper.selectList(queryWrapper);
        for (File file : files) {
            file.setDeleted(true);
            fileMapper.updateById(file);
        }
    }

    @Override
    public List<File> getAllByType(String type) {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.eq("deleted",0);
        return fileMapper.selectList(queryWrapper);
    }
}
